<template>
  <div class="lease-management-container">
    <div class="page-header">
      <h2>合同管理</h2>
    </div>
    
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="searchParams.keyword"
        placeholder="输入姓名/房号/手机号码搜索"
        class="search-input"
      >
        <template #append>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">
            搜索
          </el-button>
        </template>
      </el-input>
      <el-button type="info" icon="el-icon-download" @click="handleExport">
        导出
      </el-button>
    </div>

    <!-- 合同列表 -->
    <el-table
      v-loading="loading"
      :data="contractList"
      style="width: 100%"
      border
    >
      <el-table-column prop="contractNumber" label="合同编号" min-width="120" />
      
      <!-- 不显示合同名称 -->
      <!-- 不显示资源名称 -->
      
      <el-table-column prop="contractStatus" label="状态" min-width="100">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.contractStatus)">
            {{ getStatusName(scope.row.contractStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      
      <el-table-column prop="tenantName" label="租户" min-width="120" />
      <el-table-column prop="tenantName" label="联系人" min-width="100" />
      <el-table-column prop="tenantPhone" label="联系电话" min-width="120" />
      
      <el-table-column prop="signDate" label="签订日期" min-width="120">
        <template #default="scope">
          {{ formatDate(scope.row.signDate) }}
        </template>
      </el-table-column>
      
      <el-table-column prop="startDate" label="起租日期" min-width="120">
        <template #default="scope">
          {{ formatDate(scope.row.startDate) }}
        </template>
      </el-table-column>
      
      <el-table-column prop="endDate" label="停租日期" min-width="120">
        <template #default="scope">
          {{ formatDate(scope.row.endDate) }}
        </template>
      </el-table-column>
      
      <el-table-column prop="totalRent" label="租金" min-width="100">
        <template #default="scope">
          {{ formatMoney(scope.row.totalRent) }}
        </template>
      </el-table-column>
      
      <el-table-column label="操作" min-width="200" fixed="right">
        <template #default="scope">
          <el-button
            type="primary"
            size="small"
            text
            @click="handleChange(scope.row)"
          >
            变更
          </el-button>
          <el-button
            type="success"
            size="small"
            text
            @click="handleTermination(scope.row)"
          >
            续期
          </el-button>
          <el-button
            type="warning"
            size="small"
            text
            @click="handleRenewal(scope.row.id)"
          >
            退租
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[5, 10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 变更合同对话框 -->
    <el-dialog
      v-model="changeDialogVisible"
      title="变更合同"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="changeFormRef"
        :model="changeForm"
        label-width="120px"
        :rules="formRules"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同编号" prop="contractNumber">
              <el-input v-model="changeForm.contractNumber" placeholder="请输入合同编号" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="租户" prop="tenantName">
              <el-input v-model="changeForm.tenantName" placeholder="请输入租户" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="签订日期" prop="signDate">
              <el-date-picker
                v-model="changeForm.signDate"
                type="date"
                placeholder="选择签订日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="租赁方联系人" prop="tenantContact">
              <el-input v-model="changeForm.tenantContact" placeholder="请输入租赁方联系人" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同状态" prop="contractStatus">
              <el-select v-model="changeForm.contractStatus" placeholder="请选择合同状态">
                <el-option label="正在执行" value="0" />
                <el-option label="已到期" value="1" />
                <el-option label="已终止" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="租期(月)" prop="leaseTerm">
              <el-input v-model.number="changeForm.leaseTerm" placeholder="请输入租期(月)" type="number" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="起租日期" prop="startDate">
              <el-date-picker
                v-model="changeForm.startDate"
                type="date"
                placeholder="选择起租日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="停租日期" prop="endDate">
              <el-date-picker
                v-model="changeForm.endDate"
                type="date"
                placeholder="选择停租日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="保证金" prop="deposit">
              <el-input v-model.number="changeForm.deposit" placeholder="请输入保证金" type="number" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="中介费" prop="agencyFee">
              <el-input v-model.number="changeForm.agencyFee" placeholder="请输入中介费" type="number" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同租金总额" prop="totalRent">
              <el-input v-model.number="changeForm.totalRent" placeholder="请输入合同租金总额" type="number" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="changeForm.remark" placeholder="请输入备注" type="textarea" rows="3" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <template #footer>
        <el-button @click="changeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveContract">保存</el-button>
      </template>
    </el-dialog>
    
    <!-- 续签合同对话框 -->
    <el-dialog
      v-model="renewalDialogVisible"
      title="续签合同"
      width="400px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="renewalFormRef"
        :model="renewalForm"
        label-width="120px"
        :rules="renewalFormRules"
      >
        <el-form-item label="当前停租日期">
          <el-input
            :value="currentRenewalContract?.endDate ? formatDate(currentRenewalContract.endDate) : ''"
            disabled
          />
        </el-form-item>
        <el-form-item label="新停租日期" prop="newEndDate">
          <el-date-picker
            v-model="renewalForm.newEndDate"
            type="date"
            placeholder="选择新的停租日期"
            :disabled-date="(time: Date) => {
              if (!currentRenewalContract.value?.endDate) return false;
              const currentEndDate = new Date(currentRenewalContract.value.endDate);
              // 只能选择停租日期之后的时间
              return time.getTime() <= currentEndDate.getTime();
            }"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="renewalDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveRenewal">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue';
import { ElMessage, ElForm, ElFormItem, ElMessageBox } from 'element-plus';
import { getContractOneList, updateOneContract, renewalContract, terminationContract } from '@/api/contract';

// 搜索参数
const searchParams = ref({
  keyword: '',
});

// 加载状态
const loading = ref(false);

// 合同列表数据
const contractList = ref<any[]>([]);

// 分页数据
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 查询合同列表
const fetchContractList = async () => {
  loading.value = true;
  try {
    const params = {
      ...searchParams.value,
      pageNum: pagination.value.currentPage,
      pageSize: pagination.value.pageSize,
    };
    
    console.log('请求参数:', params);
    const response = await getContractOneList(params);
    console.log('API响应:', response);
    
    // 处理API返回的records字段数据
    if (response.code === 200 || response.code === 0 || response.code === 6) {
      // 重点处理嵌套的data.records结构，这是根据API响应截图发现的正确路径
      contractList.value = response.data?.records || response.records || response.data?.list || [];
      // 获取总条数，兼容不同的数据结构
      pagination.value.total = response.data?.total || response.total || contractList.value.length;
      
      // 只在成功时显示成功消息，且有数据时才显示
      if (contractList.value.length > 0) {
        ElMessage.success('获取合同列表成功');
      }
    } else {
      // 确保错误消息不为空且有意义
      const errorMessage = response.message && response.message !== '操作成功' 
        ? response.message 
        : '获取合同列表失败，请检查网络连接或联系管理员';
      console.error('API返回错误:', errorMessage);
      ElMessage.error('获取合同列表失败：' + errorMessage);
      contractList.value = [];
      pagination.value.total = 0;
    }
  } catch (error: any) {
    console.error('获取合同列表异常:', error);
    // 捕获具体的错误信息
    const errorMsg = error.message || '未知错误';
    ElMessage.error(`获取合同列表异常: ${errorMsg}，请稍后重试`);
    contractList.value = [];
    pagination.value.total = 0;
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.value.currentPage = 1;
  fetchContractList();
};

// 导出
const handleExport = () => {
  ElMessage.info('导出功能待实现');
};

// 变更对话框相关
const changeDialogVisible = ref(false);
const changeFormRef = ref<InstanceType<typeof ElForm>>();
const currentContractId = ref('');

// 续签对话框相关
const renewalDialogVisible = ref(false);
const renewalFormRef = ref<InstanceType<typeof ElForm>>();
const currentRenewalContract = ref<any>(null);

// 续签表单数据
const renewalForm = reactive({
  newEndDate: ''
});

// 续签表单验证规则
const renewalFormRules = reactive({
  newEndDate: [
    { required: true, message: '请选择新的停租日期', trigger: 'change' }
  ]
});

// 变更表单数据
const changeForm = reactive({
  contractNumber: '',
  tenantName: '',
  signDate: '',
  tenantContact: '',
  contractStatus: '',
  leaseTerm: '',
  startDate: '',
  endDate: '',
  deposit: '',
  agencyFee: '',
  totalRent: '',
  remark: ''
});

// 表单验证规则
const formRules = reactive({
  contractNumber: [
    { required: true, message: '请输入合同编号', trigger: 'blur' }
  ],
  tenantName: [
    { required: true, message: '请输入租户', trigger: 'blur' }
  ],
  tenantContact: [
    { required: true, message: '请输入租赁方联系人', trigger: 'blur' }
  ],
  signDate: [
    { required: true, message: '请选择签订日期', trigger: 'change' }
  ],
  contractStatus: [
    { required: true, message: '请选择合同状态', trigger: 'change' }
  ],
  leaseTerm: [
    { required: true, message: '请输入租期(月)', trigger: 'blur' },
    { type: 'number', min: 1, message: '租期不能小于1个月', trigger: 'blur' }
  ],
  startDate: [
    { required: true, message: '请选择起租日期', trigger: 'change' }
  ],
  endDate: [
    { required: true, message: '请选择停租日期', trigger: 'change' }
  ]
});

// 变更
const handleChange = (row: any) => {
  currentContractId.value = row.id;
  
  // 填充表单数据
  changeForm.contractNumber = row.contractNumber || '';
  changeForm.tenantName = row.tenantName || '';
  changeForm.signDate = row.signDate ? new Date(row.signDate) : '';
  // 使用表格行中的联系人数据填充租赁方联系人
  changeForm.tenantContact = row.tenantName || row.tenantContact || '';
  changeForm.contractStatus = String(row.contractStatus || '0');
  changeForm.leaseTerm = row.leaseTerm || '';
  changeForm.startDate = row.startDate ? new Date(row.startDate) : '';
  changeForm.endDate = row.endDate ? new Date(row.endDate) : '';
  changeForm.deposit = row.deposit || '';
  changeForm.agencyFee = row.agencyFee || '';
  changeForm.totalRent = row.totalRent || '';
  changeForm.remark = row.remark || '';
  
  // 显示对话框
  changeDialogVisible.value = true;
};

// 保存合同变更
const saveContract = async () => {
  if (!changeFormRef.value) return;
  
  await changeFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 准备提交数据
        const submitData = {
          id: Number(currentContractId.value),
          contractNumber: changeForm.contractNumber,
          tenantName: changeForm.tenantName,
          // 修正为ISO 8601格式 yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
          signDate: changeForm.signDate ? changeForm.signDate.toISOString() : '',
          tenantContract: changeForm.tenantContact,
          contractStatus: Number(changeForm.contractStatus),
          leaseTerm: Number(changeForm.leaseTerm),
          // 修正为ISO 8601格式 yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
          startDate: changeForm.startDate ? changeForm.startDate.toISOString() : '',
          // 修正为ISO 8601格式 yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
          endDate: changeForm.endDate ? changeForm.endDate.toISOString() : '',
          deposit: Number(changeForm.deposit),
          agencyFee: Number(changeForm.agencyFee),
          totalRent: Number(changeForm.totalRent),
          remark: changeForm.remark
        };
        
        const response = await updateOneContract(submitData);
        
        if (response.code === 200 || response.code === 0 || response.code === 6) {
          ElMessage.success('合同变更成功');
          changeDialogVisible.value = false;
          // 重新获取合同列表
          fetchContractList();
        } else {
          ElMessage.error(response.message || '合同变更失败');
        }
      } catch (error) {
        console.error('保存合同失败:', error);
        ElMessage.error('保存失败，请稍后重试');
      }
    }
  });
};

// 续期
const handleTermination = async (row: any) => {
  currentRenewalContract.value = row;
  renewalForm.newEndDate = '';
  renewalDialogVisible.value = true;
};

// 退租
const handleRenewal = async (id: string) => {
  try {
    // 弹出确认对话框
    await ElMessageBox.confirm(
      '确定要办理退租吗？',
      '退租确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    const response = await terminationContract(Number(id));
    if (response.code === 200 || response.code === 0 || response.code === 6) {
      ElMessage.success('退租成功');
      fetchContractList();
    } else {
      ElMessage.error(response.message || '退租失败');
    }
  } catch (error: any) {
    // 如果用户取消确认，则不显示错误消息
    if (error.name !== 'ElMessageBoxCancel') {
      console.error('退租失败:', error);
      ElMessage.error('退租失败，请稍后重试');
    }
  }
};

// 保存续签
const saveRenewal = async () => {
  if (!renewalFormRef.value || !currentRenewalContract.value) return;
  
  await renewalFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 准备提交数据
        const submitData = {
          id: Number(currentRenewalContract.value.id),
          endDate: renewalForm.newEndDate ? renewalForm.newEndDate.toISOString() : ''
        };
        
        const response = await renewalContract(submitData);
        
        if (response.code === 200 || response.code === 0 || response.code === 6) {
          ElMessage.success('续签成功');
          renewalDialogVisible.value = false;
          // 重新获取合同列表
          fetchContractList();
        } else {
          ElMessage.error(response.message || '续签失败');
        }
      } catch (error) {
        console.error('续签失败:', error);
        ElMessage.error('续签失败，请稍后重试');
      }
    }
  });
};

// 分页大小变更
const handleSizeChange = (size: number) => {
  pagination.value.pageSize = size;
  fetchContractList();
};

// 当前页码变更
const handleCurrentChange = (current: number) => {
  pagination.value.currentPage = current;
  fetchContractList();
};

// 获取状态标签类型
const getStatusTagType = (status: number): string => {
  const statusMap: Record<number, string> = {
    0: 'success', // 正在执行
    1: 'warning', // 到期
    2: 'danger',  // 终止
  };
  return statusMap[status] || 'info';
};

// 获取状态名称
const getStatusName = (status: number): string => {
  const statusMap: Record<number, string> = {
    0: '正在执行',
    1: '已到期',
    2: '已终止',
  };
  return statusMap[status] || '未知状态';
};

// 格式化日期
const formatDate = (dateStr?: string): string => {
  if (!dateStr) return '-';
  try {
    const date = new Date(dateStr);
    if (isNaN(date.getTime())) return dateStr;
    return date.toLocaleDateString('zh-CN');
  } catch (e) {
    return dateStr;
  }
};

// 格式化金额
const formatMoney = (money?: number): string => {
  if (money === undefined || money === null) return '¥0.00';
  return `¥${money.toFixed(2)}`;
};

// 页面挂载时获取数据
onMounted(() => {
  fetchContractList();
});
</script>

<style scoped>
.lease-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.search-bar {
  background-color: #fff;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 16px;
}

.search-input {
  width: 400px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
  background-color: #fff;
  padding: 16px;
  border-radius: 8px;
}
</style>